var contextRoot = '';//上下文根，不设的话在各自请求url中自行加上
var resoucesPath = '/portal/resources/';//静态资源根目录
//输入json数据 可以填充form表单  add by sly

$.fn.formEdit = function(data){
    return this.each(function(){
        var input, name;
        if(data == null){this.reset(); return; }
        for(var i = 0; i < this.length; i++){  
            input = this.elements[i];
            //checkbox的name可能是name[]数组形式
            name = (input.type == "checkbox")? input.name.replace(/(.+)\[\]$/, "$1") : input.name;
            if(data[name] == undefined) continue;
            switch(input.type){
                case "checkbox":
                    if(data[name] == ""){
                        input.checked = false;
                    }else{
                        //数组查找元素
                        if(data[name].indexOf(input.value) > -1){
                            input.checked = true;
                        }else{
                            input.checked = false;
                        }
                    }
                break;
                case "radio":
                    if(data[name] == ""){
                        input.checked = false;
                    }else if(input.value == data[name]){
                        input.checked = true;
                    }
                break;
                case "button": break;
                default: input.value = data[name];
            }
        }
    });
};
//form表单序列化  add by sly
$.fn.serializeObject = function() {
	 var o = {};
	 var a = this.serializeArray();
	 $.each(a, function() {
	 if (o[this.name] !== undefined) {
	 if (!o[this.name].push) {
	 o[this.name] = [o[this.name]];
	}
	 o[this.name].push(this.value || '');
	 } else {
	 o[this.name] = this.value || '';
	}
	});
	 return o;
	};
	
	
/***
 *退出按钮  sly
 */
var logOut = function(){
	alertMsg("确定要退出当前系统吗",1,function(){
		var obj={};
		padMarketing.ajaxNormal(
				'/pad_marketing/login/loginOut.action',
				obj,
				function (data){	
					 sessionStorage.clear();
					 location.href=data.url;
				},
				function(data){
					console.log(data);
				}
		);
	});		
}	

//普通的非空校验
//必须输入校验 add by sly
function inputCheck(form){
	var flag = false;
	var msg = "";	
	$("#"+form+" input[required='required'],select[required='required']").each(
		function(index,me,arg){
			var v = $(me).val();
			var t = $(me).parent().prev().html();
			if(t == null)
			{
				t = $(me).parent().parent().prev().html();
			}
			if(v=="" || v==null){
				msg = t+'不能为空！';
				flag = true;
				return false;
			}
	});
	
	if(flag) return [flag,msg];
	return [flag,msg];
}

//尽量ajax都走这个封装方法
window.padMarketing = {
	    ajaxNormal: function(targetUrl, sendData, callSuccess, callError, async,isShowLoading,loadingMsg) {
	    	targetUrl = contextRoot + targetUrl;
	    	if(isShowLoading==undefined||isShowLoading==true)
	    		showLoadingPad(loadingMsg);
	        $.ajax({
	            type: 'POST',
	            url: targetUrl,
	            data: {'jsonParam':JSON.stringify(sendData)},
	            dataType: 'json',
	    		async: (async==false)?async:true,
	            success: function(data) {
	            	hideLoadingPad();
	            	if(data&&data.Status){
	            		if(data.Status=='S')
	            			callSuccess(JSON.parse(data.Body));
	            		else{
	            			alertMsg?alertMsg(data.ErrMsg?data.ErrMsg:"Status：F,ErrMsg:null"):console.log(data.ErrMsg);	
	            			callError?callError({responseText:data.ErrMsg}):'';
	            		}
	            	}else
	            		callSuccess(data);
	            },
	            error: function(XMLHttpRequest, textStatus, errorThrown) {
	            	hideLoadingPad();
	            	if(XMLHttpRequest.responseText=='loseSession'){
	            		alertMsg('会话失效，请重新登陆！',0,function(){
	            			location.href = '/pad_marketing/login/index.action';
	            		});
	            	}else{
	            		if(XMLHttpRequest.status==0){
//	            			alertMsg?alertMsg("网络连接失败，请检查你的网络"):console.log(XMLHttpRequest.responseText);
	            		}else{
	            			alertMsg?alertMsg(XMLHttpRequest.responseText?XMLHttpRequest.responseText:XMLHttpRequest.status+"--操作异常"):console.log(XMLHttpRequest.responseText);		            		
	            		}
	            		callError?callError(XMLHttpRequest, textStatus, errorThrown):'';
	            	}
	            },
	            complete:function(){
	            }
	        });
	    },
	    //直连核心web接口
	    ajaxDirect: function(transNo, sendData, callSuccess, callError, async,isShowLoading){
	    	var request = this.configRequest(sendData,transNo);
	    	if(isShowLoading==undefined||isShowLoading==true)
	    		showLoadingPad();
	        $.ajax({
	        	contentType:"application/json;charset=UTF-8",
	            type: 'POST',
	            url: 'https://portal.allianz.com.cn/PortalDev/Interface/api/iPad/Call',
	            data: request,
	            dataType: 'json',
	    		async: (async==false)?async:true,
	            success: function(data) {
	            	hideLoadingPad();
	            	if(data&&data.Status){
	            		if(data.Status=='S')
	            			callSuccess(JSON.parse(data.Body));
	            		else{
	            			alertMsg?alertMsg(data.ErrMsg?data.ErrMsg:"Status：F,ErrMsg:null"):console.log(data.ErrMsg);	
	            			callError?callError({responseText:data.ErrMsg}):'';
	            		}
	            	}else
	            		callSuccess(data);
	            },
	            error: function(XMLHttpRequest, textStatus, errorThrown) {
	            	hideLoadingPad();
	            	if(XMLHttpRequest.responseText=='loseSession'){
	            		alertMsg('会话失效，请重新登陆！',1,function(){
	            			location.href = '/pad_marketing/login/index.action';
	            		});
	            	}else{
	            		alertMsg?alertMsg(XMLHttpRequest.responseText):console.log(XMLHttpRequest.responseText);
	            		callError?callError(XMLHttpRequest, textStatus, errorThrown):'';
	            	}
	            	
	            },
	            complete:function(){
	            }
	        });
	    },
	    configRequest:function(object, TransType){
	    	var request = {};
			//传递对象得到body
			var body = JSON.stringify(object);
			//NEWTOUCH@AZCL#2016
			var sign = $.md5(body+'NEWTOUCH@AZCL#2016');
			request.PartnerId = 'NEWTOUCH';
			request.TransType = TransType;
			request.Sign = sign;
			request.Body = body;
			return request;
	    }
	};
//书架查询重置
function managerReset(){	
	$('#selectForm')[0].reset(); 
}

//提交核保Gif动画
function showLoadingGif(content){
	var html = '';
	html += '<div class="loading-panel" id="loadingPad">';
	html += '<div class="loading">';
	html += '<img src="/pad_marketing/html/img/allianaGif.gif" width="100%">';
	html += '</div>';
	html += '<div class="blank-1"></div>';
	html += '<div class="blank-1"></div>';
	html += '<h4></h4>';
	html += '</div>';
	
	$("#loadingPad").remove();
	$('body').before(html);
	
	$("#loadingPad").show();
	$("#loadingPad h4").text(content||'');
}


function showLoadingPad(content){
	showLoadingGif(content);
/*	var html = '';
	html += '<div class="loading-panel" id="loadingPad">';
	html += '    <div class="loading">';
	html += '        <span></span>';
	html += '        <span></span>';
	html += '        <span></span>';
	html += '        <span></span>';
	html += '        <span></span>';
	html += '    </div>';
	html += '<h4></h4>';
	html += '</div>';	
	
	$("#loadingPad").remove();
	$('body').before(html);
	
	$("#loadingPad").show();
	$("#loadingPad h4").text(content||'');*/
}

function hideLoadingPad(){
	$("#loadingPad").hide();
}

//书架通用 add by sly  
//签名
function writeName(me,index){
	var appBase =$(me).parent().parent().parent().data("data"); 
	var status =$(me).parent().parent().parent().attr("status");  
	sessionStorage.clear();
    sessionStorage.appBase = JSON.stringify(appBase);
    window.location.href="/pad_marketing/main/sign.action?url=ordermanager/"+orderManager(index)+".action";
}
//拍照
function takePhotoM(me,index){
	var appBase =$(me).parent().parent().parent().data("data");   
	var status =$(me).parent().parent().parent().attr("status");  
	sessionStorage.clear();
	 sessionStorage.appBase = JSON.stringify(appBase);    
    window.location.href="/pad_marketing/main/cardPhoto.action?url=/pad_marketing/ordermanager/"+orderManager(index)+".action";
}

function changeManager(me,index){
	var appBase =$(me).parent().parent().parent().data("data"); 
	var status =$(me).parent().parent().parent().attr("status");  
	sessionStorage.clear();
	sessionStorage.appBase = JSON.stringify(appBase);
    if(status=="I"){
    	padMarketing.ajaxNormal(
				"/pad_marketing/main/appopen.action",
				appBase,
				function (data){
					sessionStorage.setItem("returnUrl", "/pad_marketing/ordermanager/"+orderManager(index)+".action");
   				 	window.location.href="/pad_marketing/purchaseNote/index.action";						
				},
				function(data){}
		);
    }  
}
//书架通用 add by sly
//查看订单 跳到投保须知界面
function lookManager(me,index){
	var appBase =$(me).parent().parent().parent().data("data");
	var status =$(me).parent().parent().parent().attr("status");  
	sessionStorage.clear();
    sessionStorage.appBase = JSON.stringify(appBase); 
    sessionStorage.setItem("confirmUrl", "/pad_marketing/ordermanager/"+orderManager(index)+".action");
    window.location.href="/pad_marketing/main/coverConfirm.action";     
}
//支付订单 跳到支付界面
function payMoney(me,index){
	var appBase =$(me).parent().parent().parent().data("data");
	var status =$(me).parent().parent().parent().attr("status");   
	sessionStorage.clear();
	sessionStorage.appBase = JSON.stringify(appBase);  
    if(status=="S" || status=="P" || status=="I"){
    	$("#changePayP").html("");
    	$("#payP").html("");
    	$("#makeSure").html("");
    	//在线支付直接跳
    	if(appBase.nbPaymentMethod=="02"){
    		window.location.href="/pad_marketing/main/pay.action?url=ordermanager/"+orderManager(index)+".action";
    		return;
    	}else{
    	//DDA 首先获得支付号    然后在去查询
    		var contractIdData={};
    		if(appBase.contractId){
    			contractIdData.piContractId=appBase.contractId;
    		}
    		padMarketing.ajaxNormal(
    				"/pad_marketing/main/queryDDAInfo.action",
    				contractIdData,
    				function (data){
    					if(data==null || data==undefined || data.length==0){
    						window.location.href="/pad_marketing/main/pay.action?url=ordermanager/"+orderManager(index)+".action";
    						return;
    					}else{
    						var payData ={};
    						payData.poDlBatchNo=data[0].PO_DL_BATCH_NO;
    						padMarketing.ajaxNormal(
    								"/pad_marketing/main/queryStatus.action",
    								payData,
    								function (data){
    									//传入支付号 ，返回 2 成功 ， F 失败 ，1或者空 为 进行中  ，po_return_msg 处理结果
    									if(data.retInt==2){
    										handleOrder("01",index);
    									}else if(data.retInt=="F"){
    										//失败 调错误接口显示
    										padMarketing.ajaxNormal(
    												"/pad_marketing/main/getFailReason.action",
    												contractIdData,
    												function (data){
    													if(data){
    														var reason = data.retInt;
    														padMarketing.ajaxNormal(
    			    												"/pad_marketing/main/isUnderway.action",
    			    												contractIdData,
    			    												function (data){
    			    													if(data&&data.retInt==0){
    			    														handleOrder("02",index,reason);
    			    													}else{
    			    														handleOrder("03",index);
    			    													}
    			    													
    			    												},
    			    												function(data){}
    			    										);
    														
    													}
    												},
    												function(data){}
    										);
    									}else{
    										handleOrder("03",index);
    									}
    								},
    								function(data){}
    						);
    					}
    				},
    				function(data){
    					
    				}
    		);
    	}
    }  
}
function handleOrder(flag,type,reason){
	//成功
	if(flag=="01"){
		var html="";
		html+="<p class='text-center'>该订单已支付</p>"
		$("#content").html(html);
		
		var htm="";
		htm+='<button class="btn btn-warning btn-lg" onclick="closeDiv(\'pay\')"><span class="icon icon-ok"></span>确定</button>';
		$("#makeSure").html(htm);
		showDiv("pay");
	}
	//失败
	else if(flag=="02"){
		var html="";
		html+='<label class="col-md-5 control-label">新业务交费方式</label>';
	    html+='<div class="col-md-7 orange lh-45">银行自动转账</div>'; 
	    html+='<div class="clearfix"></div>';
	    html+='<label class="col-md-5 control-label">支付失败原因</label>';   
	    html+='<div class="col-md-7 orange lh-45" id="cause">'+reason+'</div>';
	    $("#content").html(html);
	    
	    var htm="";
	    htm+='<button class="btn btn-primary btn-block"  onclick="changePayMoney(this,'+type+')"><span class="icon icon-no"></span>修改支付方式</button>';
	    $("#changePayP").html(htm);
	    
	    var ht=""
	    ht+='<button class="btn btn-warning btn-block"  onclick="payMoneyHref(this,'+type+')"><span class="icon icon-ok"></span>支付</button>'
	    $("#payP").html(ht);
	    showDiv("pay");
	}
	//在途
	else if(flag=="03"){
		var html="";
		html+="<p class='text-center'>该订单支付中</p>"
		$("#content").html(html);
		
		var htm="";
		htm+='<button class="btn btn-warning btn-lg" onclick="closeDiv(\'pay\')"><span class="icon icon-ok"></span>确定</button>';
		$("#makeSure").html(htm);
		showDiv("pay");
	}
}
//删除订单 然后刷新
function deleteManager(me,index){
	alertMsg("确定删除该订单吗？",1,function(){
		var appBase =$(me).parent().parent().parent().data("data");
		var status =$(me).parent().parent().parent().attr("status");  
	    if(status=="I"){
	    	padMarketing.ajaxNormal(
					"/pad_marketing/ordermanager/delete.action",
					appBase,
					function (data){
						alertMsg("已删除",0,function(){
							window.location.href="/pad_marketing/ordermanager/"+orderManager(index)+".action";
						});	    										
					},
					function(data){}
			);
	    } 
	});
}

//批量删除订单 然后刷新
function deleteAll(index){	
	alertMsg("确定删除订单吗？",1,function(){
		var flag=true;
		var arr=[];
		$('input:checked').each(function(index,me){
			var appBase = $(me).parent().parent().data("data");
			if(!appBase){
				appBase=$(me).closest("dl").data("data");
			}
			padMarketing.ajaxNormal(
					"/pad_marketing/ordermanager/delete.action",
					appBase,
					function (data){
						
					},
					function(data){
						flag=false;
						arr.push(app.orderId);
					}
			);
		}); 
    	if(flag){
    		alertMsg("已删除",0,function(){
				window.location.href="/pad_marketing/ordermanager/"+orderManager(index)+".action";
			});
    	}else{
    		var str;
    		for(var i in arr){
    			str+=arr[i]+',';
    		}
    		alertMsg(str+"未删除",0,function(){
				window.location.href="/pad_marketing/ordermanager/"+orderManager(index)+".action";
			});
    	}
	});	
}
//修改支付方式 
function changePay(me,index){
	var appBase =$(me).parent().parent().parent().data("data");
	var status =$(me).parent().parent().parent().attr("status");
	sessionStorage.clear();
	sessionStorage.appBase = JSON.stringify(appBase);   
    window.location.href="/pad_marketing/main/editPay.action";
    
}
//复制订单 跳到投保须知界面
function copyManager(me,index){
	var status =$(me).parent().parent().parent().attr("status");  
	var aBase =$(me).parent().parent().parent().data("data");	
	var appBase={};
	appBase.appId=aBase.appId;
	appBase.orderId=aBase.orderId;
	appBase.sign=aBase.sign;	
	padMarketing.ajaxNormal(
			"/pad_marketing/ordermanager/copy.action",
			appBase,
			function (data){
				sessionStorage.clear();
				sessionStorage.appBase = JSON.stringify(data);
				sessionStorage.setItem("returnUrl", "/pad_marketing/ordermanager/"+orderManager(index)+".action");
				window.location.href="/pad_marketing/purchaseNote/index.action";					
			},
			function(data){}
	);
   

}
/***
 * 校验身份证号码 id为身份证号码 birth为生日 add by sly
 */
var checkIdCommon = function (id,birth) {
	idOfBorth = id.substr(6, 8);
	str=birth.replace(/-/g,"");
   var re = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
   if (re.test(id) && idOfBorth == str) {
	   flag = true;
   } else {
	   flag = false;
   }
   return flag;
}
function checkString(str){
	var flag = false;
	if(str==null || str==""){
		flag=true;
	}
	return flag;
}

//-------------立即购买三要素通用start------------------
//保存被保人四要素数据，根据传入dom查询
//存储产品信息
function saveCp3MinData(dom,pkgs){	
	var inputs = $(dom).closest('.open-top').find('input');
	var name = inputs.eq(0).val();
	var dateOfBirth = inputs.eq(1).val();
	var sex = '';
	if(inputs.eq(2).parent().hasClass('active')){
		sex = 'M';
	}else{
		sex = 'F';
	}
	var jobCode = inputs.eq(4).data('selected').code;
	
	var mins = {name:name,dateOfBirth:dateOfBirth,sex:sex,ocCode:jobCode};
	//如果是模糊查询出的已有客户
	var cp = inputs.eq(0).data('app');
	if(cp){
		cp.name = name;
		cp.dateOfBirth = dateOfBirth;
		cp.sex = sex;
		cp.ocCode = jobCode;
		mins = cp;
	}else{
		mins.socialMedicare = 'Y';//是否社保默认是
	}
	
	if(!(pkgs&&pkgs.length>0)){
		pkgs = [];
		$(".check-list  input:checkbox:checked").each(function(){
			pkgs.push($(this).data('pkg'));
		});
	}
	console.log(pkgs);
	padMarketing.ajaxNormal(
			'/pad_marketing/main/type002appCreate.action',
			{mins:mins,pkgs:pkgs},
			function (data){
				console.log('成功');
				console.log(data);
				
				var appBases = data;
				if (appBases.length == 1) {
					sessionStorage.appBase = JSON.stringify(appBases[0]);
				} else {
					$('#change').remove();
					var p = '<div class="open-body font-16"  id="change"  ><p  class="add font-12 gray">请点选其中的一张订单继续投保操作</p></div>';
					$('#open3 h4').after(p);
					for (var i = 0; i < appBases.length; i++) {

						var add_risk = '<div class="show"><div class="blank-1"></div><div class="form-group"><div class="col-md-4"><p class="p-overflow" title="">'
								+ appBases[i].productName
								+ '</p></div><div class="col-md-6 text-right"><p class="p-overflow">订单号：<span class="orange">'
								+ appBases[i].orderId
								+ '</span></p> </div><div class="col-md-2 text-right"><div  class="radio_blo"><input id="input'
								+ i
								+ '" data="'
								+ appBases[i]
								+ '" type="radio" name="xx" /><label for="input'
								+ i
								+ '">&nbsp;</label></div></div></div><hr></div>';
						$('.add').append(add_risk);
					}

					$(".radio_blo input").click(
							function() {
								sessionStorage.removeItem('appBase');
								var ind = $(this).parent().parent().parent().parent().index();
								//								alert(ind);
								sessionStorage.appBase = JSON.stringify(appBases[ind]);
								if($("input[name=xx]").attr('checked')){
									$(document).on('click','#text-center',function(){
									       window.location.href = "/pad_marketing/purchaseNote/index.action";									
							        })
								}
								
							})
					showDiv('open3');
				}
				
				window.location.href = "/pad_marketing/purchaseNote/index.action";
			},
			function(data){
				console.log('失败');
				console.log(data);
			}
	);
}
//输入三要素建议书创建quoCreate
function quoCreate(dom,pkgs){
	var inputs = $(dom).closest('.open-top').find('input');
	var name = inputs.eq(0).val();
	var age = inputs.eq(1).val();
	var dateOfBirth = $('.input-group-addon').mobiscroll('getDate').Format('yyyy-MM-dd');
	var index = $('.input-group-addon').eq(0).attr("index");
	if(index!="1"){
		dateOfBirth=null;
	}
	var sex = '';
	if(inputs.eq(2).parent().hasClass('active')){
		sex = 'M';
	}else{
		sex = 'F';
	}
	var jobCode = inputs.eq(4).data('selected').code;
	
	var mins = {name:name,age:age,sex:sex,ocCode:jobCode,dateOfBirth:dateOfBirth};
	//如果是模糊查询出的已有客户
	var cp = inputs.eq(0).data('app');
	if(cp){
		cp.name = name;
		cp.age = age;
		cp.sex = sex;
		cp.ocCode = jobCode;
		cp.dateOfBirth = dateOfBirth;
		mins = cp;
	}else{
		mins.social = true;//是否社保默认是
	}
	
	if(!(pkgs&&pkgs.length>0)){
		pkgs = [];
		$(".check-list  input:checkbox:checked").each(function(){
			pkgs.push($(this).data('pkg'));
		});
	}
	console.log(pkgs);
	padMarketing.ajaxNormal(
			'/pad_marketing/main/quoCreate.action',
			{mins:mins,pkgs:pkgs},
			function (data){
				console.log(data);
				sessionStorage.quoBase = JSON.stringify(data);
				sessionStorage.returnUrl = location.href.substring(location.href.indexOf('pad_marketing')-1);
				window.location.href = '/pad_marketing/plan/proposalNew.action';
			},
			function(data){
				console.log(data);
				console.log('ajax error');
			}
		);
}


//-------------立即购买三要素通用end------------------


/***
 * 邮箱校验
 * @param str
 * @returns {Boolean}
 */
var checkEmail = function(str){
	var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
	var flag = false;
	if(re.test(str)){
		flag = true;
	}else{
		flag = false;
	}
	return flag;
}
var checkTel = function(tel,head){	
	var flag = false;
	var re = /^1\d{10}$/;
	var r  =/^[0-9]+(-[0-9]+)*$/;
	if(head=="86")
	{		
		if(re.test(tel)){
			flag = true;
		}else{
			flag = false;
		}
	}else{
		if(r.test(tel)&&head!=null&&head!=""){
			flag = true;
		}else{
			flag = false;
		}		
	}
	return flag;
}
var checkGTel=function(tel,head){
	var flag = false;
	var re=/^(0[0-9]{2,3}-)([2-9][0-9]{6,7})$/;
	var r=/^[0-9]+(-[0-9]+)*$/;
	if(head=="86")
	{
		if(re.test(tel)){
			flag = true;
		}else{
			flag = false;
		}
	}else{
		if(r.test(tel)&&head!=null&&head!=""){
			flag = true;
		}else{
			flag = false;
		}
	}
	return flag;
}
function postCode(number){
	if(!number){
		return true;
	}
	var re = /^\d{6}$/;
	if(re.test(number))
	{
		return true;
	}
	return false;
}
//只能是数字校验
function onlyNumber(me,inputDemo){
	var number = $(me).val();
	var re = /^\d*$/;
	if(number){
		if(!re.test(number))
		{
			alertMsg(inputDemo+"请填写数字");
			$(me).val("");
			return;
		}
	}	
}
//数字和一位小数校验
function onlyNumberAndLitter(me,inputDemo){
	var number = $(me).val();
	var reg = new RegExp(/^[0-9]+\.{0,1}[0-9]{0,1}$/);
	if(number){
		if(!reg.test(number))
		{
			alertMsg(inputDemo+"请正确填写");
			$(me).val("");
			return;
		}
	}	
}
function checkMail(mail){
	if(!mail){
		return true;
	}
	var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
	if(re.test(mail))
	{
		return true;
	}
	return false;
}
//截取url参数
function getQueryString(name) {  
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");  
    var r = window.location.search.substr(1).match(reg);  
    if (r != null) return unescape(r[2]);  
    return null;  
}  


/**
 * 从href获得参数
 * 
 * @param sArgName
 * @returns {String}
 */
function getArgsFromHref(sArgName)
{
	var sHref = window.location.href;
	sHref = decodeURI(sHref);
    var args = sHref.split("?");
    var retval = "";
    if(args[0] == sHref) /*参数为空*/
    {
    	return retval; /*无需做任何处理*/
    }
    var str = args[1];
    args = str.split("&");
    for(var i = 0; i < args.length; i ++){
	    str = args[i];
	    var arg = str.split("=");
	    if(arg[0] == sArgName){
	    	retval = arg[1];
	    	break;
	    }
    }
    return retval;
}


//返回按键
function returns(){
	var returnUrl = sessionStorage.getItem("returnUrl");
	location.href=returnUrl;
}

/**
 * 点击链接展示pdf，传入pdf地址
 */
function goPdfShow(pdfurl,param,ifSign){
	var host = window.location.host;
	var url = "http://" + host + encodeURI(pdfurl);
//	调壳弹出新页面，参数说明：1：回调函数名称，2：要展示的地址，3：回调函数参数，4：是否需要签字
	gotoPDF('pdfRefresh',url,param,ifSign);
}

/**
 * 客户导入
 */
//导入三要素
var cusData = JSON.parse(sessionStorage.customerData==null?JSON.stringify([]):sessionStorage.customerData);
function nameInput(){
	if(cusData.length==0){
		var tmpAlert = alertMsg;
		alertMsg=null;
		padMarketing.ajaxNormal(
				'/pad_marketing/main/appGetCPList.action',
				{},
				function(data){
					//console.log(data);
					sessionStorage.setItem("customerData", JSON.stringify(data));
					cusData=data;
					alertMsg = tmpAlert;
					
				},
				function(data){
					alertMsg = tmpAlert;
				},
				true,
				false
			);
	}
}
//清除模糊查询
function clearPerson(){
	setTimeout(function(){
		$("#searchInput").html("");
	},100);	
}
//常用职业单选事件
function clickHandler(obj){
	var something = $(".col-md-4 button[ch='ch']");
	if(something==null)
	{
		$(obj).attr("ch","ch");
	}
	something.removeAttr("ch");
	$(obj).attr("ch","ch");
}
//常用职业点击确认事件
$("#normalSure").click(function(){
	var index= $(this).attr("index");
	normalSure(index);
});
//index 标识位   赋值
function normalSure(index){
	var ocCode = $(".col-md-4 button[ch='ch']").val();
	var ocName = $(".col-md-4 button[ch='ch']").html();
	$('input[id^=mobiscroll]').eq(index==2?0:2).val(ocName).data('selected',{code:ocCode,name:ocName});
	closeDiv('open5');
}
function handleData(data,result){
	$("#"+data+"").html("");
	var html="";
	var name = $("#"+result+"").val();
	if(!name){
		return;
	}	
	var n = 0;
	var numberArr=[];
	for(var i in cusData)
	{
		if(cusData[i].name.indexOf(name)!=-1 || cusData[i].name.indexOf(name.toLocaleLowerCase())!=-1 || cusData[i].name.indexOf(name.toLocaleUpperCase())!=-1)
		{
			html+="<li onclick='inputThis(this)' style='cursor:pointer' class="+data+">"
			html+=HtmlEncode(cusData[i].name);
			html+="</li>";
			numberArr.push(i);
			n++;
		}
		if(n>=10){
			break;
		}
		
	}
	$("#"+data+"").html(html);
	$("li[onclick='inputThis(this)']").each(function(index,me){
		var n= numberArr[index];
		$(me).data("dataApp",cusData[n]);
	});
}
function inputThis(me){
	var obj = $(me).data("dataApp");
	$("#nameInput").val(obj.name);
	$("#nameInput").data("app",obj);
	$("#dataOfBirth").val(obj.dateOfBirth);	
	$('input[id^=mobiscroll]').eq(0).data('selected',{code:obj.ocCode,name:obj.coName});
	$('input[id^=mobiscroll]').eq(0).val((obj.ocName.split("/"))[2]);
	obj.sex=="M"?male(0):female(0);
	$("#searchInput").html("");
}
function male(index){
	$(".male").eq(index).attr("class","male active");
	$(".female").eq(index).attr("class","female")
}
function female(index){
	$(".female").eq(index).attr("class","female active");
	$(".male").eq(index).attr("class","male");
}

//根据年龄职业计算默认职业
function calDefOc(ageOrBirth,sex,inputDom){
	ageOrBirth = String(ageOrBirth);
	var a = /^(\d{4})-(\d{2})-(\d{2})$/;
	var isBuy = false;
	//如果传入的是出生日期，换算成年龄
	if(ageOrBirth&&a.test(ageOrBirth)){
		ageOrBirth = jsGetAge(ageOrBirth);
		//如果输入的是出生日期，说明是在线投保，在线投保18岁以后,不默认再默认职业
		isBuy = true;
	}
	var retObj = {};
	//{"code":"O02","category":"文教机关","type":"教育机构和其它","name":"文教机关/教育机构和其它/学生"}
	//<7岁——服务业/家庭管理/儿童、	7~17岁——文教机关/教育机构和其它/学生	男性18~60岁/女性18~55岁——一般内勤、	男性>60岁/女性	>55岁——退休 
	//0-17岁 儿童
	
	if(ageOrBirth<7){
		retObj.code = 'T03';
		retObj.name = '儿童';
	}else if(ageOrBirth>=7&&ageOrBirth<=17){
		retObj.code = 'O02';
		retObj.name = '学生';
	}else{
		if(!isBuy){
			if(sex=='M'){
				if(ageOrBirth>=18&&ageOrBirth<=60){
					retObj.code = 'A01';
					retObj.name = '内勤人员';
				}else if(ageOrBirth>60){
					retObj.code = 'T04';
					retObj.name = '退休者';
				}
			}else{
				if(ageOrBirth>=18&&ageOrBirth<=55){
					retObj.code = 'A01';
					retObj.name = '内勤人员';
				}else if(ageOrBirth>55){
					retObj.code = 'T04';
					retObj.name = '退休者';
				}
			}
		}
	}
	var selected = $(inputDom).data('selected');
	if(!selected||!selected.type)
		retObj.name?$(inputDom).val(retObj.name).data('selected',retObj):$(inputDom).val(null).data('selected',null);
	return retObj;
}
//出生日期算年龄
//JS日期系列：根据出生日期 得到周岁年龄               
//参数strBirthday已经是正确格式的2007-02-09这样的日期字符串
function jsGetAge(strBirthday)
{       
  var returnAge = null;
  var strBirthdayArr=strBirthday.split("-");
  var birthYear = strBirthdayArr[0];
  var birthMonth = strBirthdayArr[1];
  var birthDay = strBirthdayArr[2];
  
  var d = new Date();
  var nowYear = d.getFullYear();
  var nowMonth = d.getMonth() + 1;
  var nowDay = d.getDate();
  if(nowYear>=birthYear){
	  returnAge = nowYear - birthYear;
	  if(nowMonth>birthMonth){
		  
	  }else if(nowMonth<birthMonth){
		  returnAge--;
	  }else if(nowMonth==birthMonth){
		  if(nowDay>=birthDay){
			  
		  }else{
			  returnAge--;
		  }
	  }
  }
  return returnAge;
}
//四要素默认值带入
function initCarrer(index,demo){
	var ageOrBirth =  $("#"+demo+"").val();
	var sex        =  $(".active").eq(index).attr("name");
	var inputDom   =  $('input[id^=mobiscroll]').eq(index==0?0:2);
	calDefOc(ageOrBirth,sex,inputDom);
}

function showDiv2(id,e){
    
    $("#"+id).animate({left:'10%'});
    $("#"+id).css("display","block");
}

function closeDiv2(id){

   $("#"+id).animate({left:'100%'});
   setTimeout(function () {
     $("#"+id).css("display","none");
    
  },1000)

}

//判断三要素是否填写完整,未填写完整弹窗提醒，填写完整关闭

function alt(id){
	var flag = true;
	if($(id)){
		console.log($(id));
		$(id).find("input[type=text],input[type=number]").each(function(i,me){
			if(i!=0&&i!=3){			
				   if($(me).val()==""||$(me).val()==null){
					   flag = false;
					   return flag;			   
				   }	
			}
		   	   
		})
		return flag;
	}
}



//其他投保选项方法
//续期缴费判断
function needRenewPayment(appBase){
	if(appBase.paymentMode=="01"){
		return appBase.hasRegularRiders;
	}
	if(appBase.productGroup5=="ONE YEAR TERM"){
		return appBase.autoRenew=="Y";
	}
	return true;
}
//缴费账户判断
function needPayment(appBase){
	if(appBase.nbPaymentMethod=="01"){
		return true;
	}	
	return needRenewPayment(appBase);
}


//点击进度条跳转url统一使用此方法，num为第几步，appBase根据需要传可为空
function gotoStep(num,appBase){
	if(appBase){
		sessionStorage.setItem("appBase",appBase);
	}
	switch(num){
		case 1:window.location.href='/pad_marketing/purchaseNote/index.action';
		break;
		case 2:window.location.href='/pad_marketing/cover/cover.action';
		break;
		case 3:window.location.href='/pad_marketing/main/gotoOther.action';
		break;
		case 4:window.location.href='/pad_marketing/main/gotoHealthContent.action';
		break;
		case 5:window.location.href='/pad_marketing/main/gotoCoverPrompt.action';
		break;
		default:
			console.log('num参数错误！num='+num);
	}
}
//强中弱
//校验包含数字
function checkIsNum(str){
	var i = 0;
	for(var n =0;n<str.length;n++){
		var flag = isNaN(str.charAt(n));
		if(!flag){
			i=1;
			return i;
		}
	}
	return i;
}
//校验包含英文
function checkIsEn(str){
	var reg = /^[A-Za-z]$/;
	var i = 0;
	for(var n =0;n<str.length;n++){
		var flag = reg.test(str.charAt(n));
		if(flag){
			i=1;
			return i;
		}
	}
	return i;
}
//校验包含特殊字符
function checkIsSp(str){
	var reg = /^[!@#$%^&*()_+|\?<>~‘“'"~！@#￥%……&*（）——+{}【】]+$/;
	var i = 0;
	for(var n =0;n<str.length;n++){
		var flag = reg.test(str.charAt(n));
		if(flag){
			i=1;
			return i;
		}
	}
	return i;
}
function getStrong(str){
	var I = checkIsNum(str);
	var J = checkIsEn(str);
	var K = checkIsSp(str);
	return I+J+K;
}
function checkStrong(me){
	var N = getStrong($(me).val());

	switch (N)
	{
	case 1:		
	  $("#strongTh").attr("class","pw-strength  pw-default pw-weak");
	  break;
	case 2:
		 $("#strongTh").attr("class","pw-strength  pw-default pw-medium");
	  break;
	case 3:
		 $("#strongTh").attr("class","pw-strength  pw-default pw-strong");
	  break;
	default:
	 alertMsg("请输入您的新密码");
	}
}
/***
	格式化
 	*@params money {Number or String} 金额
	*@params digit {Number} 小数点的位数，不够补0
	*@returns {String} 格式化后的金额	  
**/
function formatMoney(money, digit){
	digit = digit||2;
	var tpMoney = '-';
	if (money||money === 0) {
		tpMoney = money;
	}
	tpMoney = new Number(tpMoney);
	if (isNaN(tpMoney)) {
		return '-';
	}
	tpMoney = tpMoney.toFixed(digit) + '';
	var re = /^(-?\d+)(\d{3})(\.?\d*)/;
	while (re.test(tpMoney)) {
		tpMoney = tpMoney.replace(re, "$1,$2$3")
	}
	return tpMoney;
}
function orderManager(index){
	switch(index){
	case 1:return "index";
	break;
	case 2:return "date";
	break;
	case 3:return "list";
	break;
	default:
		return "index";
	}
}
var HtmlEncode = function(str){
    var hex = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
    var preescape = str;
    var escaped = "";
    if(preescape == null || preescape == undefined){
        return escaped;
    }
    for(var i = 0; i < preescape.length; i++){
        var p = preescape.charAt(i);
        escaped = escaped + escapeCharx(p);
    }
    
    return escaped;
                    
    function escapeCharx(original){
        var found=true;
        var thechar=original.charCodeAt(0);
        switch(thechar) {
            case 10: return "<br/>"; break; //newline
            case 32: return "&nbsp;"; break; //space
            case 34:return "&quot;"; break; //"
            case 38:return "&amp;"; break; //&
            case 39:return "&#x27;"; break; //'
            case 47:return "&#x2F;"; break; // /
            case 60:return "&lt;"; break; //<
            case 62:return "&gt;"; break; //>
            case 198:return "&AElig;"; break;
            case 193:return "&Aacute;"; break;
            case 194:return "&Acirc;"; break; 
            case 192:return "&Agrave;"; break; 
            case 197:return "&Aring;"; break; 
            case 195:return "&Atilde;"; break; 
            case 196:return "&Auml;"; break; 
            case 199:return "&Ccedil;"; break; 
            case 208:return "&ETH;"; break;
            case 201:return "&Eacute;"; break; 
            case 202:return "&Ecirc;"; break; 
            case 200:return "&Egrave;"; break; 
            case 203:return "&Euml;"; break;
            case 205:return "&Iacute;"; break;
            case 206:return "&Icirc;"; break; 
            case 204:return "&Igrave;"; break; 
            case 207:return "&Iuml;"; break;
            case 209:return "&Ntilde;"; break; 
            case 211:return "&Oacute;"; break;
            case 212:return "&Ocirc;"; break; 
            case 210:return "&Ograve;"; break; 
            case 216:return "&Oslash;"; break; 
            case 213:return "&Otilde;"; break; 
            case 214:return "&Ouml;"; break;
            case 222:return "&THORN;"; break; 
            case 218:return "&Uacute;"; break; 
            case 219:return "&Ucirc;"; break; 
            case 217:return "&Ugrave;"; break; 
            case 220:return "&Uuml;"; break; 
            case 221:return "&Yacute;"; break;
            case 225:return "&aacute;"; break; 
            case 226:return "&acirc;"; break; 
            case 230:return "&aelig;"; break; 
            case 224:return "&agrave;"; break; 
            case 229:return "&aring;"; break; 
            case 227:return "&atilde;"; break; 
            case 228:return "&auml;"; break; 
            case 231:return "&ccedil;"; break; 
            case 233:return "&eacute;"; break;
            case 234:return "&ecirc;"; break; 
            case 232:return "&egrave;"; break; 
            case 240:return "&eth;"; break; 
            case 235:return "&euml;"; break; 
            case 237:return "&iacute;"; break; 
            case 238:return "&icirc;"; break; 
            case 236:return "&igrave;"; break; 
            case 239:return "&iuml;"; break; 
            case 241:return "&ntilde;"; break; 
            case 243:return "&oacute;"; break;
            case 244:return "&ocirc;"; break; 
            case 242:return "&ograve;"; break; 
            case 248:return "&oslash;"; break; 
            case 245:return "&otilde;"; break;
            case 246:return "&ouml;"; break; 
            case 223:return "&szlig;"; break; 
            case 254:return "&thorn;"; break; 
            case 250:return "&uacute;"; break; 
            case 251:return "&ucirc;"; break; 
            case 249:return "&ugrave;"; break; 
            case 252:return "&uuml;"; break; 
            case 253:return "&yacute;"; break; 
            case 255:return "&yuml;"; break;
            case 162:return "&cent;"; break; 
            case '\r': break;
            default:
                found=false;
                break;
        }
        if(!found){
            if(thechar>127) {
                var c=thechar;
                var a4=c%16;
                c=Math.floor(c/16); 
                var a3=c%16;
                c=Math.floor(c/16);
                var a2=c%16;
                c=Math.floor(c/16);
                var a1=c%16;
                return "&#x"+hex[a1]+hex[a2]+hex[a3]+hex[a4]+";";        
            }
            else{
                return original;
            }
        }    
    }
}


//输入框点击软键盘go（前往）按钮，关闭软键盘
$(function(){
	downKeyboard();
});
var downKeyboard = function(){
	$('input').keydown(function(event){
		if(event.keyCode==13){
			this.blur();
		}
	})
}

//拆分电话
function splitForT(tel){
	var arr=[];
	if(tel){
		arr=tel.split("-");
	}
	return arr;
}

//判断是否国内
function isChina(nationality){
	if(nationality==407 || nationality==408 || nationality==425 || nationality==437){
		return true;
	}
	return false;
}
//拼接电话
function addForT(splitOne,splitTwo){
	var split = splitOne+splitTwo;
	if(split){
		var splitAll;
		splitAll=splitOne+"-"+splitTwo;
		return splitAll;
	}
	return '';	
}

//建议书，根据出生日期起计算年龄
function OnDateOfBirthChange(birth,spanFlag){
	var params = {};
	params.dateOfBirth = birth;
	padMarketing.ajaxNormal(
			'/pad_marketing/main/quoGetAge.action',
			params,
			function(data){
				$(spanFlag).prev().val(data.age).trigger('change',true).trigger('input');
				$('.input-group-addon').eq(0).attr("index","1");
			},
			function(){
				
			},false);
}

//对Date的扩展，将 Date 转化为指定格式的String
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
//例子： 
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
//(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
 var o = {
     "M+": this.getMonth() + 1, //月份 
     "d+": this.getDate(), //日 
     "h+": this.getHours(), //小时 
     "m+": this.getMinutes(), //分 
     "s+": this.getSeconds(), //秒 
     "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
     "S": this.getMilliseconds() //毫秒 
 };
 if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
 for (var k in o)
 if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
 return fmt;
}

//提取俩数组中的相同元素,合并为一个新数组
function extractRepeat(array1,array2){
	//做比较的两个数组
//	var array1 = ['a','b','c','d','e'];//数组1
//	var array2 = ['d','f','e','a','p'];//数组2

	//临时数组存放
	var tempArray1 = [];//临时数组1
	var tempArray2 = [];//临时数组2

	for(var i=0;i<array2.length;i++){
	    tempArray1[array2[i]]=true;//将数array2 中的元素值作为tempArray1 中的键，值为true；
	}

	for(var i=0;i<array1.length;i++){
		if(tempArray1.hasOwnProperty(array1[i])){
	        tempArray2.push(array1[i]);//过滤array1 中与array2 相同的元素；
	    }
	}
	console.log(tempArray2);
	return tempArray2;
}
//保单号补全12位
function policyRefTo12(policyRef){
	if(!policyRef)
		return '';
	policyRef = String(policyRef);
	if(policyRef.length>=12)
		return policyRef;
	var digit = 12-policyRef.length;
	var preRef = '';
	for(var i=0;i<digit;i++){
		preRef+='0';
	}
	return preRef+policyRef;
}

